#!/bin/sh

#
# Verify can detect corruption to FAT writes
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

$HAS_WRITE_SHIM || exit 77

cat >$CONFIG <<EOF
define(BOOT_PART_OFFSET, 63)
define(BOOT_PART_COUNT, 77238)

file-resource 1K.bin {
	host-path = "${TESTFILE_1K}"
}

mbr mbr-a {
    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
}
task complete {
	on-init {
                mbr_write(mbr-a)
                fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
        }
        on-resource 1K.bin {
                fat_write(\${BOOT_PART_OFFSET}, "1K.bin")
        }
}
EOF

$FWUP_CREATE -c -f $CONFIG -o $FWFILE

# Sanity check that there are no issues normally
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete --verify-writes
rm "$IMGFILE"
$FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete --no-verify-writes

# Check that corruption is various places is detected

# Corrupt MBR
rm "$IMGFILE"
if WRITE_SHIM_CORRUPT_OFFSET=0 $FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete --verify-writes; then
    echo "Expected MBR corruption to be detected."
    exit 1
fi

# Corrupt boot partition (63 * 512)
rm "$IMGFILE"
if WRITE_SHIM_CORRUPT_OFFSET=32256 $FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete --verify-writes; then
    echo "Expected FAT header corruption to be detected."
    exit 1
fi

# Corrupt boot partition in FAT block that's beyond 256KB (512 * 512)
rm "$IMGFILE"
if WRITE_SHIM_CORRUPT_OFFSET=262144 $FWUP_APPLY -a -d $IMGFILE -i $FWFILE -t complete --verify-writes; then
    echo "Expected FAT header corruption to be detected."
    exit 1
fi

# Check that the verify logic works on this file
$FWUP_VERIFY -V -i $FWFILE
